<!--
 * @FilePath     : /study_code/vue2.x/js-get-node.html
 * @Description  : 获取节点
 * @Date         : 2025-05-03 10:39:42
 * @Author       : Fang YingGui
 * @LastEditors  : fangyinggui 18715384437@163.com
 * @LastEditTime : 2025-05-03 10:39:43
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>documentName</title>
    <link rel="stylesheet" href="" />
  </head>
  <body>
    <div id="app">
      <anchored-heading :level="4">
        Hello world!
        <p>商标lotut</p>
      </anchored-heading>
    </div>

    <script src="/vue/dist/vue.min.js"></script>
    <script src="./common.js"></script>
    <script>
      /**
       * @brief: 获取节点文本
       * @param {*} children
       * @return {*}
       * 若节点为文本，则返回节点文本；
       * 否则，会再自调用，拼接所有文本节点
       */
      var getChildrenTextContent = function (children) {
        return children
          .map(function (node) {
            return node.children ? getChildrenTextContent(node.children) : node.text
          })
          .join('')
      }

      Vue.component('anchored-heading', {
        render: function (createElement) {
          // console.log(this.$slots.default); // 这里得到 VNode （组件内）
          // 创建 kebab-case 风格的 ID
          var headingId = getChildrenTextContent(this.$slots.default)
            .toLowerCase()
            .replace(/\W+/g, '-')
            .replace(/(^-|-$)/g, '')

          console.log(headingId) // 'hello-world'

          return createElement('h' + this.level, [
            createElement(
              'a',
              {
                attrs: {
                  name: headingId,
                  href: '#' + headingId,
                },
              },
              this.$slots.default
            ),
          ])
        },
        props: {
          level: {
            type: Number,
            required: true,
          },
        },
      })

      var app = new Vue({
        el: '#app',
        data: function () {
          return {}
        },
      })
    </script>
  </body>
</html>
